package com.tjc.policytree;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @Author: tjc
 * @description
 * @Date Created in 22:51 2022-06-15
 * 分发模板
 */
public abstract class StrategyTemplate<P, R> {
    private StrategyHandler<P, R> defaultStrategyHandler = StrategyHandler.DEFAULT;

    @PostConstruct
    public void abstractInit() {
        strategyMapper = registerStrategyMapper();
        Objects.requireNonNull(strategyMapper, "strategyMapper cannot be null");
    }
    //路由定义
    protected interface StrategyMap<P, R> {
        StrategyHandler<P, R> get(P param);
    }
    private StrategyMap<P, R> strategyMapper;
    // 分发逻辑
    protected abstract StrategyMap<P, R> registerStrategyMapper();

    public R applyStrategy(P param) {
        final StrategyHandler<P, R> strategyHandler = strategyMapper.get(param);
        if (strategyHandler != null) {
            return strategyHandler.apply(param);
        }
        return defaultStrategyHandler.apply(param);
    }

    public StrategyHandler<P, R> getDefaultStrategyHandler() {
        return defaultStrategyHandler;
    }

    public void setDefaultStrategyHandler(StrategyHandler<P, R> defaultStrategyHandler) {
        this.defaultStrategyHandler = defaultStrategyHandler;
    }
}
